package com.sgb.kjwl.view.ui.activity.manage;

import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;

import androidx.annotation.Nullable;
import androidx.databinding.DataBindingUtil;

import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.maps.AMap;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.UiSettings;
import com.amap.api.maps.model.BitmapDescriptorFactory;
import com.amap.api.maps.model.CameraPosition;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.Marker;
import com.amap.api.maps.model.MarkerOptions;
import com.amap.api.services.core.AMapException;
import com.amap.api.services.core.LatLonPoint;
import com.amap.api.services.core.PoiItem;
import com.amap.api.services.geocoder.GeocodeResult;
import com.amap.api.services.geocoder.GeocodeSearch;
import com.amap.api.services.geocoder.RegeocodeQuery;
import com.amap.api.services.geocoder.RegeocodeResult;
import com.amap.api.services.poisearch.PoiResult;
import com.amap.api.services.poisearch.PoiSearch;
import com.sgb.kjwl.AppActivity;
import com.sgb.kjwl.R;
import com.sgb.kjwl.databinding.ActivityJingyingMapSearchBinding;
import com.sgb.kjwl.model.LocationAddressInfo;
import com.sgb.kjwl.view.ui.adapter.manage.JingYingGaodeSearchAdapter;
import com.swgk.core.util.MToast;

import java.util.ArrayList;
import java.util.List;

/**
 * 企业经营->地图查找->高德地图地址搜索
 */

public class JingYingMapSearchActivity extends AppActivity implements PoiSearch.OnPoiSearchListener,
        View.OnClickListener,
        GeocodeSearch.OnGeocodeSearchListener,
        AMap.OnCameraChangeListener {


    private ArrayList<LocationAddressInfo> list = new ArrayList<>();

    private ActivityJingyingMapSearchBinding binding;
    private JingYingGaodeSearchAdapter adapter;

    private String keyWord = "";// 要输入的poi搜索关键字
    private PoiResult poiResult; // poi返回的结果
    private int currentPage = 0;// 当前页面，从0开始计数
    private PoiSearch.Query query;// Poi查询条件类
    private PoiSearch poiSearch;// POI搜索
    private String searchCity = "";//要搜索的城市

    private AMap aMap;//地图对象

    private GeocodeSearch geocoderSearch;
    private LatLng latLng;
    private String addressName;
    private double lat, lng;

    public static void start(AppActivity activity, double lat, double lng, String addr, String city) {
        Intent intent = new Intent(activity, JingYingMapSearchActivity.class);
        intent.putExtra("lat", lat);
        intent.putExtra("lng", lng);
        intent.putExtra("addr", addr);
        intent.putExtra("city", city);
        activity.startActivityForResult(intent, 1);
    }

    private void iniExtra() {
        Intent intent = getIntent();
        addressName = intent.getStringExtra("addr");
        lat = intent.getDoubleExtra("lat", 0.0);
        lng = intent.getDoubleExtra("lng", 0.0);
        searchCity = intent.getStringExtra("city");
    }

    @Override
    protected void initView() {
        binding = DataBindingUtil.setContentView(this, R.layout.activity_jingying_map_search);
        binding.ivBack.setOnClickListener(this);
        binding.tvUseAddr.setOnClickListener(this);
        adapter = new JingYingGaodeSearchAdapter(this, list);
        binding.rv.setAdapter(adapter);
        adapter.setCallback(bean -> {
            addressName = bean.getText();
            lat = bean.getLat();
            lng = bean.getLon();
            binding.tvAddr.setText(addressName);
            binding.rv.setVisibility(View.GONE);
            aMap.moveCamera(CameraUpdateFactory.changeLatLng(new LatLng(bean.getLat(), bean.getLon())));
        });
        initEdit();
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        iniExtra();
        aMap = binding.mapView.getMap();
        binding.mapView.onCreate(msavedInstanceState);
        aMap.setOnCameraChangeListener(this);
        geocoderSearch = new GeocodeSearch(this);
        geocoderSearch.setOnGeocodeSearchListener(this);
        //设置显示定位按钮 并且可以点击
        UiSettings settings = aMap.getUiSettings();

        // 是否显示定位按钮
        settings.setMyLocationButtonEnabled(false);
        settings.setZoomControlsEnabled(false);
        // 是否可触发定位并显示定位层
        aMap.setMyLocationEnabled(false);
        aMap.moveCamera(CameraUpdateFactory.zoomTo(14));
        if (lat != 0.0) {
            aMap.moveCamera(CameraUpdateFactory.changeLatLng(new LatLng(lat, lng)));
            setMarket(new LatLng(lat, lng));
            binding.tvAddr.setText(addressName);
        }

    }


    private void initEdit() {
        binding.editSearch.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
            }

            @Override
            public void afterTextChanged(Editable editable) {
                keyWord = binding.editSearch.getText().toString();
                if (!TextUtils.isEmpty(keyWord)) {
                    doSearchQuery(keyWord);
                }
            }
        });
    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        switch (v.getId()) {
            case R.id.iv_back:
                finish();
                break;
            case R.id.tv_use_addr:
                if (!TextUtils.isEmpty(addressName)) {
                    Bundle bundle = new Bundle();
                    bundle.putString("addr", addressName);
                    bundle.putDouble("lat", lat);
                    bundle.putDouble("lon", lng);

                    Intent intent = getIntent();
                    intent.putExtras(bundle);
                    setResult(RESULT_OK, intent);
                }
                finish();
                break;
        }
    }

    /**
     * 开始进行poi搜索
     */
    protected void doSearchQuery(String key) {
        currentPage = 0;
        //不输入城市名称有些地方搜索不到
        // 第一个参数表示搜索字符串，第二个参数表示poi搜索类型，第三个参数表示poi搜索区域（空字符串代表全国）
        query = new PoiSearch.Query(key, "", searchCity);
        query.setPageSize(100);
        query.setPageNum(currentPage);
        poiSearch = new PoiSearch(this, query);
        poiSearch.setOnPoiSearchListener(this);
        poiSearch.searchPOIAsyn();
    }


    @Override
    public void onPoiSearched(PoiResult result, int rCode) {
        if (rCode == AMapException.CODE_AMAP_SUCCESS) {
            if (result != null && result.getQuery() != null) {
                if (result.getQuery().equals(query)) {
                    poiResult = result;
                    List<PoiItem> poiItems = poiResult.getPois();
                    list.clear();
                    for (PoiItem item : poiItems) {
                        LatLonPoint llp = item.getLatLonPoint();
                        double lon = llp.getLongitude();
                        double lat = llp.getLatitude();
                        String title = item.getTitle();
                        StringBuilder sb = new StringBuilder();
                        sb.append(item.getCityName());
                        sb.append(item.getBusinessArea());
                        sb.append(item.getSnippet());
                        list.add(new LocationAddressInfo(title, sb.toString(), lon, lat, keyWord, 0));
                    }
                    adapter.notifyDataSetChanged();
                    if (list.size() > 1) {
                        binding.rv.setVisibility(View.VISIBLE);
                    } else {
                        binding.rv.setVisibility(View.GONE);
                    }
                }
            } else {
                MToast.showToast(JingYingMapSearchActivity.this, "无搜索结果");
                binding.rv.setVisibility(View.GONE);
            }
        } else {
            MToast.showToast(JingYingMapSearchActivity.this, "错误码");
        }
    }

    @Override
    public void onPoiItemSearched(PoiItem poiItem, int i) {
    }


    @Override
    public void onCameraChange(CameraPosition cameraPosition) {
    }

    @Override
    public void onCameraChangeFinish(CameraPosition cameraPosition) {
        latLng = cameraPosition.target;
        lat = latLng.latitude;
        lng = latLng.longitude;
        getAddress(latLng);
    }

    @Override
    public void onRegeocodeSearched(RegeocodeResult result, int rCode) {
        if (rCode == 1000) {
            if (result != null && result.getRegeocodeAddress() != null && result.getRegeocodeAddress().getFormatAddress() != null) {
                addressName = result.getRegeocodeAddress().getFormatAddress(); // 逆转地里编码不是每次都可以得到对应地图上的opi
                binding.tvAddr.setText(addressName);
                setMarket(latLng);
            }
        }
    }

    @Override
    public void onGeocodeSearched(GeocodeResult geocodeResult, int i) {
    }

    public void getAddress(final LatLng latLng) {
        LatLonPoint latLonPoint = new LatLonPoint(latLng.latitude, latLng.longitude);
        RegeocodeQuery query = new RegeocodeQuery(latLonPoint, 500, GeocodeSearch.AMAP);
        geocoderSearch.getFromLocationAsyn(query);// 设置同步逆地理编码请求
    }

    private Marker mGPSMarker;
    private MarkerOptions markOptions;

    private void setMarket(LatLng latLng) {
        if (mGPSMarker != null) {
            mGPSMarker.remove();
        }
        int width = binding.mapView.getWidth() / 2;
        int height = binding.mapView.getHeight() / 2;
        markOptions = new MarkerOptions();
        markOptions.draggable(true);//设置Marker可拖动
        markOptions.icon(BitmapDescriptorFactory.fromResource(R.mipmap.icon_weizhi_3));
        //设置一个角标
        mGPSMarker = aMap.addMarker(markOptions);
        //设置marker在屏幕的像素坐标
        mGPSMarker.setPosition(latLng);
        mGPSMarker.setPositionByPixels(width, height);
        binding.mapView.invalidate();
    }


    @Override
    protected void onResume() {
        super.onResume();
        binding.mapView.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
        binding.mapView.onPause();
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        binding.mapView.onSaveInstanceState(outState);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        binding.mapView.onDestroy();
    }


}
